package com.ocp.macro.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ocp.macro.annotation.AutowireUserToken;
import com.ocp.macro.entity.*;
import com.ocp.macro.enums.DataCode;
import com.ocp.macro.exception.MysqlException;
import com.ocp.macro.mapper.dealer.DealListMapper;
import com.ocp.macro.mapper.dealerAccount.DealerAccountMapper;
import com.ocp.macro.mapper.operate.OperateMapper;
import com.ocp.macro.service.DealerAccountService;
import com.ocp.macro.utils.GsonUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class DealerAccountServiceImpl implements DealerAccountService {
    private final static String DEALER_DEFAULT_PASSWORD = "$2a$10$CwFKceXNpSb.CBejKMWDw.7Zpc9HREBPoH7yPs5BRltHIQzCoQNAq";
    private final static Integer[] SUB_DEALER_AUTHORITY_ID_ARRAYS = {2};
    @Resource
    private OperateMapper operateMapper;
    @Resource
    private DealerAccountMapper dealerAccountMapper;
    @Resource
    private DealListMapper dealListMapper;

    @Override
    public String accountUsernameExists(String username, String loginType) {
        Map<String, Object> map = new HashMap<>();

        if ("operate".equals(loginType)){
            Operate account = operateMapper.selectOperateOne(username);
            if (account!=null){//存在返回 成功
                map.put("code", DataCode.SUCCESS.getCode());
                map.put("message", DataCode.SUCCESS.getMessage());
                return GsonUtils.toJson(map);
            }
        }else if ("dealer".equals(loginType)){
            DealerAccount dealerAccount = new DealerAccount();dealerAccount.setUserName(username);
            DealerAccount account = dealerAccountMapper.selectDealerAccountOne(dealerAccount);
            if (account!=null){
                map.put("code", DataCode.SUCCESS.getCode());
                map.put("message", DataCode.SUCCESS.getMessage());
                return GsonUtils.toJson(map);
            }
        }

        map.put("code", DataCode.FAIL.getCode());
        map.put("message", DataCode.FAIL.getMessage());

        return GsonUtils.toJson(map);
    }

    @Override
    @AutowireUserToken
    public String getLoginUserInfo(UserInfoToken userInfoToken) {
        Map<String, Object> map = new HashMap<>();
        map.put("userName", userInfoToken.getUsername());

        map.put("code", DataCode.SUCCESS.getCode());
        map.put("message", DataCode.SUCCESS.getMessage());

        return GsonUtils.toJson(map);
    }

    @Override
    public String dealerNameIsExists(String dealerName){
        DealerAccount dealerAccount = new DealerAccount();
        dealerAccount.setDealName(dealerName);
        DealerAccount account = dealerAccountMapper.selectDealerAccountOne(dealerAccount);
        Map<String, Object> map = new HashMap<>();
        if (account==null){ // 不存在返回 成功
            map.put("code", DataCode.SUCCESS.getCode());
            map.put("message", DataCode.SUCCESS.getMessage());
            return GsonUtils.toJson(map);
        }

        map.put("code", DataCode.FAIL.getCode());
        map.put("message", DataCode.FAIL.getMessage());

        return GsonUtils.toJson(map);
    }

    /**
     * 实现：孙历
     * @param realNos
     * @param subAcctId
     * @return
     */
    @Override
    public String addDealerAccountListRel(List<String> realNos, Integer subAcctId) {
        Map<String,Object> map=new HashMap<String,Object>();
        List<String> newrealnos = new ArrayList<>();
        for (String string:realNos){
            string = string.replace("[","").replace("\"","").replace("]","");
            newrealnos.add(string);
        }
        Integer flag = dealListMapper.addDealerAccountListRel(newrealnos,subAcctId);
        map.put("新增记录：",flag);
        map.put("code",DataCode.SUCCESS.getCode());
        map.put("message",DataCode.SUCCESS.getMessage());
        return GsonUtils.toJson(map);
    }

    /**
     * 实现：孙历
     * 请求该总帐号下的所有子账号，根据dealerAccount封装的信息筛选
     * @param dealerAccount
     * @return
     */
    @Override
    @AutowireUserToken
    public String selectDealerSubAccountList(DealerAccount dealerAccount,UserInfoToken userInfoToken) {
        Map<String,Object> map=new HashMap<String,Object>();
        PageHelper.startPage(dealerAccount.getPage(), dealerAccount.getRows()); // 分页，设置当前页和每页条数
        dealerAccount.setDealAccountId(userInfoToken.getUserId());
        List<DealerAccount> subaccounts=dealerAccountMapper.selectDealerSubAccountList(dealerAccount);//获取子账号信息
        PageInfo<DealerAccount> pageInfo = new PageInfo <>(subaccounts);//分页信息
        if(subaccounts==null||subaccounts.size()==0){
            map.put("code",DataCode.NO_USER_MESSAGE.getCode());
            map.put("message",DataCode.NO_USER_MESSAGE.getMessage());
        }
        else{
            map.put("pageInfo",pageInfo);
            map.put("code",DataCode.SUCCESS.getCode());
            map.put("message",DataCode.SUCCESS.getMessage());
        }
        return GsonUtils.toJson(map);
    }

    /**
     * 实现：孙历
     * 请求新增经销商子账号
     * @param dealerAccount
     * @return
     */
    @Override
    @AutowireUserToken
    public String addDealerSubAccount(DealerAccount dealerAccount,UserInfoToken userInfoToken) {
        Map<String,Object> map = new HashMap<String, Object>();
        String username= dealerAccount.getUserName();
        Integer flag = dealerAccountMapper.selectDealInfoByUserName(username);//查验用户名是否重复
        if(flag!=null&&flag>0){
            DataCode.FAIL.setMessage("用户名重复，请重新输入！");
            map.put("code", DataCode.FAIL.getCode());
            map.put("message", DataCode.FAIL.getMessage());
            return GsonUtils.toJson(map);
        }
            dealerAccount.setMainId(userInfoToken.getUserId());
            dealerAccount.setDealPwd(DEALER_DEFAULT_PASSWORD);
            dealerAccount.setCreateDate(new Date());
            dealerAccount.setModifyDate(new Date());
            Integer count=dealerAccountMapper.insertDealerAccount(dealerAccount);
            if (count!=null && count>0){
                count = dealerAccountMapper.insertDealerAccountAuthorities(dealerAccount.getDealAccountId(),
                        Arrays.asList(SUB_DEALER_AUTHORITY_ID_ARRAYS)); // 进行授权
                if (count==null || count<=0)
                    throw new MysqlException(DataCode.INSERT_EXCEPTION);
            }
            else{
                throw new MysqlException(DataCode.INSERT_EXCEPTION);
            }

            if(count==0){
                DataCode.FAIL.setMessage("新增经销商信息失败");
                map.put("code", DataCode.FAIL.getCode());
                map.put("message", DataCode.FAIL.getMessage());
            }else{
                DataCode.SUCCESS.setMessage("新增经销商信息成功");
                map.put("code",DataCode.SUCCESS.getCode());
                map.put("message",DataCode.SUCCESS.getMessage());
            }
        return GsonUtils.toJson(map);
    }

    /**
     * 实现：孙历
     * 删除经销商信息
     */
    @Override
    @AutowireUserToken
    public String dealerSubAccountDelete(List<Integer> subaccount) {
        Map<String,Object> map = new HashMap<>();
        Integer flag = dealerAccountMapper.delDealerSubAccountDelete(subaccount);
        if(flag==0){
            DataCode.FAIL.setMessage("删除经销商信息失败");
            map.put("code", DataCode.FAIL.getCode());
            map.put("message", DataCode.FAIL.getMessage());
        }else{
            DataCode.SUCCESS.setMessage("删除经销商信息成功");
            map.put("code",DataCode.SUCCESS.getCode());
            map.put("message",DataCode.SUCCESS.getMessage());
        }
        return GsonUtils.toJson(map);
    }

    /**
     * 实现：孙历
     * 批量请求所选的 经销商子账号 进行 账号状态设置
     * 和传的status字段的值：0禁用，1启用
     */
    @Override
    @AutowireUserToken
    public String dealerSubAccountState(Integer state,List<Integer> subaccount) {
        Map<String,Object> map = new HashMap<>();
        Integer flag= dealerAccountMapper.dealerSubAccountState(state,subaccount);
        if(flag==0){
            DataCode.FAIL.setMessage("修改经销商状态失败");
            map.put("code", DataCode.FAIL.getCode());
            map.put("message", DataCode.FAIL.getMessage());
        }else{
            DataCode.SUCCESS.setMessage("修改经销商状态成功");
            map.put("code",DataCode.SUCCESS.getCode());
            map.put("message",DataCode.SUCCESS.getMessage());
        }
        return GsonUtils.toJson(map);
    }

    /**
     * 实现：孙历
     * 经销商子账号进行信息修改请求
     * @param dealerAccount 新的子账号信息
     */
    @Override
    @AutowireUserToken
    public String dealerSubAccountModify(DealerAccount dealerAccount) {
        Map<String,Object> map = new HashMap<>();
        Integer flag= dealerAccountMapper.dealerSubAccountModify(dealerAccount);
        if(flag!=1){
            DataCode.FAIL.setMessage("修改经销商信息失败");
            map.put("code", DataCode.FAIL.getCode());
            map.put("message", DataCode.FAIL.getMessage());
        }else{
            DataCode.SUCCESS.setMessage("修改经销商信息成功");
            map.put("code",DataCode.SUCCESS.getCode());
            map.put("message",DataCode.SUCCESS.getMessage());
        }
        return GsonUtils.toJson(map);
    }


    /**
     * 实现：孙历
     * 请求当前登录的账号所关联的经销商信息
     */
    @Override
    @AutowireUserToken
    public String dealerAccountDistrList(UserInfoToken userInfoToken){
        Map<String,Object> map = new HashMap<String, Object>(); //用map封装实体类的键值对
        Integer dealAccountId = userInfoToken.getUserId();//获取经销商账号ID
        List<String> relationId = dealListMapper.dealerAccList(dealAccountId);//通过经销商账户ID获取关联表的经销商编号集合
        if(relationId.size()==0){//判断经销商ID是否关联经销商信息
            DataCode.NO_USER_MESSAGE.setMessage("该用户未关联经销商信息");
            map.put("message",DataCode.NO_USER_MESSAGE.getMessage());//返回message信息
            map.put("code",DataCode.NO_USER_MESSAGE.getCode());//返回状态码
        }else {
            List<DealList> dealerinfo=dealListMapper.dealerInfo(relationId); //根据集合里的经销商编号获取经销商信息
            map.put("dealerinfo", dealerinfo);//封装关联的经销商信息
            map.put("code",DataCode.SUCCESS.getCode());//返回状态码
            map.put("message",DataCode.SUCCESS.getMessage());//返回message信息
        }
        return GsonUtils.toJson(map);//返回键值对用JSON切面类处理
    }

    /**
     * 实现：孙历
     * 重置经销商密码
     * @param subAcctId
     * @return
     */
    @Override
    public String dealerAccountResetPwd(Integer[] subAcctId) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();//密码处理切面类
        Map<String,Object> map = new HashMap<String, Object>(); //用map封装实体类的键值对
        String encode = encoder.encode("123456");//加密
        Integer flag=dealerAccountMapper.dealerAccountResetPwd(subAcctId,encode);//重置密码
        if(flag==subAcctId.length){
            DataCode.SUCCESS.setMessage("重置密码成功");
            map.put("code",DataCode.SUCCESS.getCode());//返回状态码
            map.put("message",DataCode.SUCCESS.getMessage());//返回message信息
        }else{
            DataCode.FAIL.setMessage("重置密码失败！");
            map.put("code", DataCode.FAIL.getCode());
            map.put("message", DataCode.FAIL.getMessage());
        }
        return GsonUtils.toJson(map);
    }
}
